import Router from '@koa/router'
import { defaultStorage as storage } from '../infra/storage.mjs'
import { logger } from '../infra/logger.mjs'
import { uuid } from '../util/random.mjs'
import { defaultMysqlConfigCenter as config } from '../infra/config/center.mjs'
import fetch from 'node-fetch'

interface SendCodeBody {
  phone?: unknown
}

interface VerifyCodeBody {
  phone?: unknown
  code?: unknown
}

const CODE_TTL_MS = 10 * 60 * 1000

function generateVerificationCode(): string {
  return Math.floor(100000 + Math.random() * 900000).toString()
}

export const authRouter = new Router()

authRouter.post('/send', async (ctx) => {
  const body = ctx.request.body as SendCodeBody | undefined
  const phone = typeof body?.phone === 'string' ? body.phone.trim() : ''

  if (!phone) {
    ctx.status = 400
    ctx.body = {
      success: false,
      msg: '手机号不可为空',
      data: null
    }
    return
  }

  const code = generateVerificationCode()
  const expireAt = new Date(Date.now() + CODE_TTL_MS)
  await storage.createAuthCode(phone, code, expireAt)
  logger.info('AuthRouter_send: verification code generated', { phone })

  // get https://push.spug.cc/send/w0byPj9G058pYQVL?code=1234&targets=18531024352
  const response = await fetch(`https://push.spug.cc/send/${config.get('sms.spug.template-id')}?code=${code}&targets=${phone}`)
  /*
  {
    "code": 200,
    "msg": "请求成功",
    "request_id": "lxGd8JlPLOxj2bn0"
  }
  */
  logger.info('AuthRouter_send: response', { response })
  const data = await response.json() as { code: number, msg: string, request_id: string }
  if (data.code !== 200) {
    ctx.status = 500
    ctx.body = {
      success: false,
      msg: '发送验证码失败',
      data: null
    }
    return
  }

  ctx.body = {
    success: true,
    msg: '验证码已发送',
    data: null
  }
})

authRouter.post('/verify', async (ctx) => {
  const body = ctx.request.body as VerifyCodeBody | undefined
  const phone = typeof body?.phone === 'string' ? body.phone.trim() : ''
  const code = typeof body?.code === 'string' ? body.code.trim() : ''

  if (!phone || !code) {
    ctx.status = 400
    ctx.body = {
      success: false,
      msg: '手机号或验证码不可为空',
      data: null
    }
    return
  }

  const validCode = await storage.findValidAuthCode(phone, code)
  if (!validCode) {
    ctx.status = 400
    ctx.body = {
      success: false,
      msg: '验证码无效或已过期',
      data: null
    }
    return
  }

  await storage.markAuthCodeStatus(validCode.id, 'VERIFIED')

  const user = await storage.findOrCreateUserByPhone(phone)
  const token = uuid()
  await storage.createUserToken(user.id, token)

  ctx.body = {
    success: true,
    msg: '验证成功',
    data: {
      token
    }
  }
})

